package com.iwop.moto.utils;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.Notification;
import com.iwop.moto.comm.Comm;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2016/7/6.
 */
public class PushNoticeUtil {
    static Logger logger=Logger.getLogger(PushNoticeUtil.class);
    static JPushClient storePush = new JPushClient(Comm.JPUSH_STORE_SERT,Comm.JPUSH_STORE_KEY);
    static JPushClient userPush = new JPushClient(Comm.JPUSH_USER_SERT,Comm.JPUSH_USER_KEY);

    /**
     * content 发送的内容
     * type ：user发送给用户端，store发送给维修店
     * users：发送对象
     * */
    public static PushResult sendPersonNotice(String content,String type,String... users){
        PushPayload payload=null;
        if (users==null||users.length==0){
            payload=getAll(content);
        }else{
            payload=getPerson(content, users);
        }
        try {
            PushResult result=null;
            if(type.equals("user")){
                result = userPush.sendPush(payload);
            }else {
                result = storePush.sendPush(payload);
            }
            logger.info("消息结果result： " +result);
            return result;
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
            return null;
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
            logger.info("Msg ID: " + e.getMsgId());
            return null;
        }
    }


    /**
     * content 发送的内容
     * type ：user发送给用户端，store发送给维修店
     * deviceId：设备id
     * type：user发送给用户端，store发送给维修店
     * */
    public static PushResult sendPersonNoticeMessage(String content,String type,String deviceId,String... users){
        PushPayload payload=sendExtraMessage(content,deviceId, users);
        try {
            PushResult result=null;
            if(type.equals("user")){
                result = userPush.sendPush(payload);
            }else {
                result = storePush.sendPush(payload);
            }
            logger.info("消息结果result： " +result);
            return result;
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
            return null;
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
            logger.info("Msg ID: " + e.getMsgId());
            return null;
        }
    }

    //附加额外消息
    public static PushPayload sendExtraMessage(String content,String deviceId,String... users) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(users))
                .setNotification(Notification.alert(content))
                .setMessage(Message.newBuilder()
                        .setMsgContent(deviceId)
                        .addExtra("from", "JPush")
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(Comm.IOSJPUSH)
                        .build())
                .build();
    }

    private static PushPayload getAll(String content){
        return PushPayload.alertAll(content);
    }

    /**
     * 别名推送
     * */
    private static PushPayload getPerson(String content,String... users){
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(users))
                .setNotification(Notification.alert(content))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(Comm.IOSJPUSH)
                        .build())
                .build();
    }

    /**
     * 标签推送
     * */
    private static PushPayload getTagContent(String tag,String content){
            return PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.newBuilder()
                            .addAudienceTarget(AudienceTarget.tag(tag))
                            .build())
                    .setMessage(Message.newBuilder()
                            .setMsgContent(content)
                            .build())
                    .setOptions(Options.newBuilder()
                            .setApnsProduction(true)
                            .build())
                    .build();
    }

    /**
     * 发送文字通知
     * */
    public static PushResult sendNotice(String text,String type,String applyName,String audisType,String... users){
            PushPayload payload=null;
            String jsonData="";
            if(StringUtils.isEmpty(text)){
                jsonData=applyName+"的"+audisType+"申请需要您的审批";
            }else {
                jsonData=text;
            }
            payload=getPerson(jsonData,users);
            PushResult result = null;
            try {
                if(type.equals("user")){
                    result = userPush.sendPush(payload);
                }else {
                    result = storePush.sendPush(payload);
                }
                logger.info("消息结果result： " +result);
            } catch (APIConnectionException e) {
                logger.error("Connection error. Should retry later. ", e);
            } catch (APIRequestException e) {
                logger.error("Error response from JPush server. Should review and fix it. ", e);
                logger.info("HTTP Status: " + e.getStatus());
                logger.info("Error Code: " + e.getErrorCode());
                logger.info("Error Message: " + e.getErrorMessage());
                logger.info("Msg ID: " + e.getMsgId());
            }
            return result;
    }


    /**
     * 发送标签推送
     * */
    public static PushResult sendTagNotice(String tag,String type,String content){
        PushPayload payload=getTagContent(tag,content);
        PushResult result = null;
        try {
            if(type.equals("user")){
                result = userPush.sendPush(payload);
            }else {
                result = storePush.sendPush(payload);
            }
            logger.info("消息结果result： " +result);
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
            logger.info("Msg ID: " + e.getMsgId());
        }
        return result;
    }


    public static String[] getWeeks(String[] arr) {
        Map map = new HashMap();
        map.put("1", "周一");
        map.put("2", "周二");
        map.put("3", "周三");
        map.put("4", "周四");
        map.put("5", "周五");
        map.put("6", "周六");
        map.put("7", "周日");
        String[] as=new String[arr.length];
        if (arr.length > 0) {
            for (int i = 0; i < arr.length; i++) {
                as[i]= (String)map.get(arr[i]);
            }
        }
        return as;
    }

}
